﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using CWB.Web.DB;

namespace CWB.Web.CacheLayer
{
    public static class AgentCache
    {
        private static Hashtable agentcache = new Hashtable();
        private static readonly object syncRoot = new object();

        public static List<AgentUserCacheInfo> getagentcache()
        {
            List<AgentUserCacheInfo> lbuci = new List<AgentUserCacheInfo>() { };
            lbuci = agentcache.Values.Cast<AgentUserCacheInfo>().ToList();
            return lbuci;
        }

        public static void Add(DbModuleAgent u)
        {
            if ((agentcache.ContainsKey(u.Loginid)))
            {
                agentcache.Remove(u.Loginid);
            }
            agentcache.Add(u.Loginid, new AgentUserCacheInfo()
            {
                u = u,
                ExpireDataTime = DateTime.Now.AddHours(12)
            });
        }

        public static void Remove(string LoginId)
        {
            lock (syncRoot)
            {
                if ((agentcache.ContainsKey(LoginId)))
                {
                    agentcache.Remove(LoginId);
                }
            }
        }

        public static AgentUserCacheInfo Get(string LoginId)
        {
            if ((agentcache.ContainsKey(LoginId)))
            {
                return (AgentUserCacheInfo)agentcache[LoginId];
            }
            else
            {
                throw new Exception(string.Format("The Agent is not exist({0})", LoginId));
            }
        }

        public static bool isExpired(Trading trading)
        {
            if (agentcache.ContainsKey(trading.userName))
            {
                AgentUserCacheInfo buci = (AgentUserCacheInfo)agentcache[trading.userName];
                if (buci.ExpireDataTime > DateTime.Now)
                {
                    return !(buci.u.chk == trading.chk);
                }
                else
                {
                    agentcache.Remove(trading.userName);
                    return true;
                }
            }
            else
            {
                return true;
            }
        }

        public class AgentUserCacheInfo
        {
            public DbModuleAgent u { get; set; }
            public DateTime ExpireDataTime { get; set; }
        }
    }
}
